import React from 'react'
import PropTypes from 'prop-types'
import { inject, observer } from 'mobx-react'

import { withStyles } from 'material-ui/styles'
import ThumbUp from 'material-ui-icons/ThumbUp'
// import xss from 'xss'
import dateFormat from '../../util/date_format'
import TopicsDetailStore from '../../stores/topic_detail'
import UserStore from '../../stores/user_store'
// marked工具
import marked from '../../util/marked'

import style from './styles'


@inject((stores) => {
  const store = {
    user: stores.user,
    topicDetail: stores.topicDetail,
  }
  return store
})
@observer
class CommentItem extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isUped: props.comment.isUped,
      upCount: props.comment.ups.length,
    }
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(loginName) {
    const { topicDetail, comment, user } = this.props
    if (!user.isLogin) {
      alert('请登陆后再操作')
      return
    } else if (user.userInfo.loginName === loginName) {
      return
    }
    topicDetail.upReply(comment.id).then((res) => {
      this.setState(preState => ({
        isUped: res === 'up',
        upCount: res === 'up' ? preState.upCount + 1 : preState.upCount - 1,
      }))
    }).catch(msg => alert(msg)) //eslint-disable-line
  }
  render() {
    const {
      comment,
      floor,
      classes,
    } = this.props
    const date = dateFormat(comment.create_at, 'yyyy-mm-dd hh:mm:ss')
    const commentContent = marked(comment.content)
    return (
      <div className={classes.item}>
        <div style={{ overflow: 'hidden' }}>
          <div className={classes.avatar}>
            <img
              className={classes.avatarImg}
              src={comment.author.avatar_url}
              alt={comment.author.loginname}
            />
          </div>
          <div className={classes.author}>
            <span className={classes.nickName}>
              <span className={classes.floor}>{floor + 1}楼</span>
              {comment.author.loginname}
            </span>

            <span className={classes.createTime}>评论于：{date}</span>
          </div>
          <div className={classes.up}>
            <ThumbUp
              className={this.state.isUped ? classes.upedIcon : classes.upIcon}
              onClick={() => this.handleClick(comment.author.loginname)}
            />
            <span className={classes.upCount}>{this.state.upCount}</span>
          </div>
        </div>
        <div
          className={classes.commentContent}
          dangerouslySetInnerHTML={{ __html: commentContent }}
        />
      </div>
    )
  }
}
export default withStyles(style)(CommentItem)
CommentItem.propTypes = {
  classes: PropTypes.objectOf(Object),
  comment: PropTypes.objectOf(Object),
  floor: PropTypes.number,
  topicDetail: PropTypes.instanceOf(TopicsDetailStore),
  user: PropTypes.instanceOf(UserStore),
}
